<?php

namespace App\Http\Models;


use Illuminate\Database\Eloquent\Model;

class Question extends Model
{
    //

    public function add()
    {

    	if(!user_ins()->is_logged_in()){
        return ['status'=>0,'msg'=>'user not login'];
      }
      if(!rq('title'))
      return['status'=>0 ,'msg'=>'requeire title'];

     $this->title = rq('title');
     $this->user_id = session('user_id');


     if(rq('desc'))
     $this->desc =rq('desc');

     return $this->save() ?
     ['status'=>1,'id'=>$this->user_id] :
     ['status'=>0,'msg'=>'db insert failed'];

    }


    public function change()
    {
      if(!user_ins()->is_logged_in()){
        return ['status'=>0,'msg'=>'user not login'];
      }
      if (!rq('id'))
        return ['status'=>0,'msg'=>'id is requeire'];

        $question = $this->find(rq('id'));
        if(!$question)

        return ['status'=>0,'msg'=>'question not exits'];



        if($question->user_id != session('user_id'))
        return ['status'=>0,'msg'=>'permissin denned'];

        if(rq('title'))

        $question->title = rq('title');

        if(rq('desc'))
        $question->desc =rq('desc');


       return $question->save() ?
       ['status'=>1] :
       ['status'=>0,'msg'=>'question update fauiled'];

    }

    public function read()
    {
     if(rq('id'))
     return[ 'status'=>1,'data'=>$this->find(rq('id'))];
     $limit = rq('limit') ?: 15;

     $skip= ((rq('page') ?: 1)-1) * $limit;
     $r= $this

     ->orderBy('created_at')
     ->limit($limit)
     ->skip($skip)
     ->get(['id','title','desc','user_id','created_at','updated_at'])
     ->keyBy('id');



     return ['status'=>1,'data'=>$r];


    }

    public function remove()
    {
      if(!user_ins()->is_logged_in())
        return ['status'=>0,'msg'=>' requeired login'];
     if(!rq('id'))

        return ['status'=>0,'msg'=>'id is requeired'];
        
        $question = $this->find(rq('id'));
    if(!$question)

       return ['status'=>0,'msg'=>'question not exits'];

    if(session('user_id') != $question->user_id)
      return ['status'=>0,'msg'=>'permission denied'];

      return $question->delete() ?
        ['status'=>1] :
         ['status'=>0,'msg'=>'db delete faiule'];
    }
}
